<template>
  <el-button
    icon="el-icon-download"
    :size="buttonSize"
    :type="buttonType"
    :disabled="exportLoading"
    :loading="exportLoading"
    @click="exportClick"
    >{{ exportLoading ? "正在导出" : "导出" }}</el-button
  >
</template>
<script>
import axios from "axios";
import { getToken } from "@/utils/auth";
import { string } from "yargs";

export default {
  props: {
    title: String, // Excel名称
    action: {
      type: String,
      default: "/asset/integral/v1/userDetail/export",
    },
    buttonType:{
      type:String,
      default:'primary'
    },
    buttonSize:{
      type:String,
      default:'small'
    },
    params: {
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      exportLoading: false,
    };
  },
  methods: {
    exportClick() {
      this.exportLoading = true;

      const API = process.env.VUE_APP_BASE_API + this.action;
      axios
        .get(API, {
          params: this.params,
          responseType: "arraybuffer",
          headers: {
            // 'Content-Type':	'application/octet-stream;charset=UTF-8',
            "X-Access-Token": getToken(),
          },
        })
        .then((res) => {
          this.handleData(res);
        })
        .finally(() => {
          this.exportLoading = false;
        });
    },

    handleData(res) {
      const blob = new Blob([res.data]);
      const downloadElement = document.createElement("a");
      const href = window.URL.createObjectURL(blob); // 创建下载的链接
      downloadElement.href = href;
      downloadElement.download = this.title + ".xls"; // 下载后文件名
      document.body.appendChild(downloadElement);
      downloadElement.click(); // 点击下载
      document.body.removeChild(downloadElement); // 下载完成移除元素
      window.URL.revokeObjectURL(href); // 释放掉blob对象
    },
  },
};
</script>
<style lang="scss" scoped>
</style>
